package com.skytech.component.monitor.enterprise_data_monitoring;

import com.alibaba.fastjson.JSONObject;
import com.skytech.component.monitor.data.MonitorData;
import com.skytech.component.monitor.util.ChromeBrowser;
import com.skytech.component.monitor.util.SaveDataUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ShangDongService implements CrawlerScript {


    @Autowired
    private SaveDataUtil saveDataUtil;

    @Autowired
    private ChromeBrowser chromeBrowser;

    private static final String province = "山东";

    private static final Logger log = LoggerFactory.getLogger(ShangDongService.class);


    public void start() {

        ChromeDriver driver = chromeBrowser.getChromeDriver();
        try {
            driver.get("http://58.56.98.78:8405/index.htm");//打开山东网页
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            List<JSONObject> jsonObjects = new ArrayList<>();
            partClickNext(driver, jsonObjects, null);
            detailData(driver, jsonObjects);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            driver.quit();
        }


    }

    private void detailData(ChromeDriver driver, List<JSONObject> jsonObjects) {
        for (JSONObject jsonObject : jsonObjects) {
            driver.get(jsonObject.get("href").toString());
            List<MonitorData> monitorDataList = new ArrayList<>();
            partBodyClickNext(driver, null, jsonObject, monitorDataList);

            if (!monitorDataList.isEmpty()) {
                saveDataUtil.saveTag(monitorDataList, province);
            }

        }

    }

    private void partClickNext(ChromeDriver driver, List<JSONObject> jsonObjects, String html) {
        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        if (html != null) {
            if (html.equals(htmlNew)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlNew;
        Elements allElements = parse.getAllElements();
        Elements elementsNew = allElements.select(".nrright .datagrid-view .datagrid-view2 .datagrid-body .datagrid-btable");
        if (!elementsNew.isEmpty()) {
            Elements elements = allElements.select(".nrright .datagrid-view .datagrid-view2 .datagrid-body .datagrid-btable").get(0).getElementsByTag("tr");

            for (Element e : elements) {
                JSONObject jsonObject = new JSONObject();
                String s = e.select(".datagrid-cell.datagrid-cell-c1-详情").get(0).getElementsByTag("span").attr("onclick");
                jsonObject.put("城市", e.select(".datagrid-cell.datagrid-cell-c1-CityName").text());
                jsonObject.put("区县", e.select(".datagrid-cell.datagrid-cell-c1-AreaName").text());
                jsonObject.put("企业名称", e.select(".datagrid-cell.datagrid-cell-c1-EntName").text());
                jsonObject.put("企业类别", e.select(".datagrid-cell.datagrid-cell-c1-EntTypeName").text());
                String url = "http://58.56.98.78:8405/ND/" + s.split("/")[1] + "/" + s.split("/")[2] + "/" + s.split("/")[3];
                jsonObject.put("href", url);
                jsonObjects.add(jsonObject);
            }
            try {
                WebElement element = driver.findElementByXPath("/html/body/div[1]/div[2]/div[4]/div[2]/div/div[2]/div/div[3]/div/div/div[2]/table/tbody/tr/td[10]/a/span/span[2]");


                element.click();
                log.info(driver.getCurrentUrl());
                Thread.sleep(1000);
                partClickNext(driver, jsonObjects, html);
            } catch (Exception e) {
                log.error("{}--超时--{}", driver.getCurrentUrl(), e.getMessage());
                return;
            }

        }
    }

    public void partBodyClickNext(ChromeDriver driver, String html, JSONObject jsonObject, List<MonitorData> monitorDataList) {
        String htmlNew = driver.findElementByTagName("html").getAttribute("outerHTML");
        Document parse = Jsoup.parse(htmlNew, driver.getCurrentUrl());
        if (html != null) {
            if (html.equals(htmlNew)) {
                log.error("两次链接内容相同,当前页{}", driver.getCurrentUrl());
                return;
            }
        }
        html = htmlNew;
        Elements allElements = parse.getAllElements();
        Elements elementstmp = allElements.select(".Bjb_cont2>div.panel.datagrid.easyui-fluid .datagrid-view .datagrid-view2 .datagrid-body .datagrid-btable").get(0).getElementsByTag("tr");

        if (!elementstmp.isEmpty()) {
            for (Element e : elementstmp) {
                MonitorData monitorData = new MonitorData();
                // JSONObject jsonObjectBody = new JSONObject();
                monitorData.setProvince(province);
                monitorData.setId(UUID.randomUUID().toString());
                monitorData.setCity(jsonObject.getString("城市"));
                monitorData.setArea(jsonObject.getString("区县"));
                monitorData.setCompanyName(jsonObject.getString("企业名称"));
                monitorData.setIndustry(jsonObject.getString("企业类型"));
                monitorData.setMonitorPoint(e.select(".datagrid-cell.datagrid-cell-c3-Subname").text());
                monitorData.setMonitorInfo(e.select(".datagrid-cell.datagrid-cell-c3-Itemname").text());
                monitorData.setMonitorTime(e.select(".datagrid-cell.datagrid-cell-c3-Ac005_datetime").text());
                monitorData.setMonitorType(e.select(".datagrid-cell.datagrid-cell-c3-Typecode").text());
                monitorData.setMonitorValue(e.select(".datagrid-cell.datagrid-cell-c3-Ac005_value").text());
                monitorData.setMonitorStandardValue(e.select(".datagrid-cell.datagrid-cell-c3-Stander").text());
                monitorData.setOverproof(e.select(".datagrid-cell.datagrid-cell-c3-Ac005_cbbs").text());
                monitorData.setCrawlingTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                monitorDataList.add(monitorData);
            }
        }
        try {
            WebElement element = driver.findElement(By.xpath("//div[@class='Bjb_cont2']/div[@class='panel datagrid easyui-fluid']//div[@class='datagrid-pager pagination']//a[@class='l-btn l-btn-small l-btn-plain']//span[@class='l-btn-icon pagination-next']"));
            element.click();
            log.info(driver.getCurrentUrl());
            Thread.sleep(3000);
            partBodyClickNext(driver, html, jsonObject, monitorDataList);
        } catch (Exception e) {
            log.error("{}--子页面点击下一页超时--{}", driver.getCurrentUrl(), e.getMessage());

            return;
        }

    }


}
